<?php defined('SYSPATH') or die('No direct script access.');

class Uploader  {
  
    public $tmp_name = '';
    public $name = '';
    public $extension = '';
    public $size = 0;
    private $stream = false;
  
    private function __construct() {}
    
    static public function factory($url = null)
    {
          
            $uploader  = new Uploader();
            if($url)
            {
                //TODO: change to CURL

                if($file = file_get_contents($url))
                {
                     $tmp_name = tempnam(sys_get_temp_dir(), 'temp');    
                     file_put_contents($tmp_name, $file);
                     
                     $uploader->tmp_name = $tmp_name;
                     $uploader->name = pathinfo($url, PATHINFO_FILENAME);;
                     $uploader->extension = strtolower(pathinfo($url, PATHINFO_EXTENSION));
                     $uploader->size = filesize($tmp_name);
                      
                }
                else
                {
                    throw new Exception('Can\'t connect to'.$url);
                }
            }
            else
            {
                if (isset($_GET['qqfile'])) 
                {
                    $uploader->stream = true;
                     $input = fopen('php://input', 'r');

                     $tmp_name = tempnam(sys_get_temp_dir(), 'temp');    
                     file_put_contents($tmp_name, $input);


                    $uploader->tmp_name = $tmp_name;
                    $uploader->name = pathinfo($_GET['qqfile'], PATHINFO_FILENAME);;
                    $uploader->extension = strtolower(pathinfo($_GET['qqfile'], PATHINFO_EXTENSION));
                    $uploader->size = filesize($tmp_name);

                }
                elseif (isset($_FILES['qqfile'])) 
                {
                    $uploader->tmp_name = $_FILES['qqfile']['tmp_name'];  
                    $uploader->name = pathinfo($_FILES['qqfile']['name'], PATHINFO_FILENAME);
                    $uploader->extension = strtolower(pathinfo($_FILES['qqfile']['name'], PATHINFO_EXTENSION));
                    $uploader->size = $_FILES['qqfile']['size'];

                }
                else
                {
                    throw new Exception('unknown error');
                }
            }

            return $uploader;
    }
    

    public function validate( $size, array $allowed_extensions)
    {
        $size = $this->toBytes($size);
                    
        if(isset($_SERVER['CONTENT_LENGTH']) AND $_SERVER['CONTENT_LENGTH'] != $this->size AND $this->stream)
        {
            return array('error'=> __(Kohana::message('validation', 'file_streaming'))); //No files were uploaded.
        }
       
        if ($this->size == 0)
        {
            return array('error' => __(Kohana::message('validation', 'empty_file'))); //'File is empty.'
        }
        
        if ($this->size > $size)
        {
            return array('error' => __(Kohana::message('validation', 'max_file_size'))); //File is to large.
        }
        
         if(!in_array(strtolower($this->extension), $allowed_extensions)){
            $these = implode(', ', $allowed_extensions);
            return array('error' => __(Kohana::message('validation', 'file_extension'))); //File has an invalid extension, it should be one of '. $these . '.
        }
                
    }
    
    private function toBytes($str)
    {
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }
}